function EEG = cvc_edat_epochs(EEG,edatfile)
% CVC_EDAT_EPOCHS
%
%  Synopsis
%  ========
%
%  EEG = cvc_edat_epochs(EEG,edatfile)
%
%  -- Author: Mads Dyrholm --
%     Center for Visual Cognition, University of Copenhagen.
%     April 2010
%
%  Purpose
%  =======
%
%  Import the edat columns into epoch field of EEG structure.
%
%  Inputs
%  ======
%
%  EEG - EEGLAB data structure.
%
%  edatfile - Name of file which was exported with EdataAid 
%  as an 'Excel text' file (with *no* unicode!).
%
%  Outputs
%  =======
%
%  EEG.epoch(:).edat_* - imported columns with name *.

qq=textread(edatfile,'%s','delimiter','\n');
ww = textscan(qq{2},'%s','delimiter','\t');
MM = length(qq)-2;
fprintf('CVC: Found %i trials in the edat file. \n',MM);
NN = length([ww{:}]);
ww = ww{1};
fprintf('CVC: Found %i columns in the edat file. \n',NN);
EDAT = cell(MM,NN);
for ii=1:MM
  ee = textscan(qq{ii+2},'%s','delimiter','\t');
  for jj=1:NN
    EDAT{ii,jj} = ee{1}(jj);
  end
end

if MM~=EEG.trials
  warning(sprintf('EDAT missing epochs will be resolved using eventurevent field. (EDAT has %i rows, EEG has %i trials).',MM,EEG.trials));
  huske = [];
  for epo=1:EEG.trials
    urepoch = unique([EEG.epoch(epo).eventurevent{find([EEG.epoch(epo).eventlatency{:}]==0)}]);
    huske = cat(2,huske,urepoch);
  end
  skiprows = setdiff(1:MM,huske);
else
  skiprows = [];
end

for column = 1:NN
  fieldnam = [strrep(ww{column},'.','_')];
  fieldnam = [strrep(fieldnam,'[','_')];
  fieldnam = [strrep(fieldnam,']','_')];
  fieldnam = ['edat_' fieldnam];
  fprintf('Importing: %s\n',fieldnam);
  
  epo = 1;
  for row = 1:MM
    if ismember(row,skiprows), continue, end
    cc = textscan(qq{row+2},'%s','delimiter','\t');
    cc = cc{:};
    tmp = cc{column};
    eval(sprintf('EEG.epoch(%i).%s=''%s'';',epo,fieldnam,tmp));
    epo = epo + 1;
  end
end
